package 数据结构.链表;

/**
 * @author Zhu
 * @Description
 * @create 2023-02-20
 */
public class JZ18删除链表的节点 {

    //虚拟头节点
    public ListNode deleteNode (ListNode head, int val) {
        // write code here
        ListNode newhead = new ListNode(-1);
        newhead.next = head;
        ListNode cur = head;
        ListNode pre = newhead;
        while (cur != null){
            if(cur.val == val){
                pre.next = cur.next;
            }
            pre = cur;
            cur = cur.next;
        }
        return newhead.next;
    }

    //遍历找到要删除的节点
    public ListNode deleteNode2 (ListNode head, int val) {
        // write code here
        if(head.val == val)
            return head.next;

        ListNode res = head;
        while(head.next.val != val){
            head = head.next;
        }
        head.next = head.next.next;
        return res;
    }
}
